from typing import Optional
from model import Model
from translator.pdf_parser import PDFParser
from translator.writer import Writer
from utils import LOG
from requests.exceptions import Timeout as RequestsTimeout
class PDFTranslator:
    def __init__(self, model: Model):
        self.model = model
        self.pdf_parser = PDFParser()
        self.writer = Writer()

    def translate_pdf(self, pdf_file_path: str, file_format: str = 'PDF', target_language: str = '中文', output_file_path: str = None, pages: Optional[int] = None):
        self.book = self.pdf_parser.parse_pdf(pdf_file_path, pages)
        max_retries = 3
        retry_count = 0

        for page_idx, page in enumerate(self.book.pages):
            for content_idx, content in enumerate(page.contents):
                prompt = self.model.translate_prompt(content, target_language)
                LOG.debug(prompt)

                while retry_count < max_retries:
                    try:
                        translation, status = self.model.make_request(prompt, target_language)
                        LOG.info(translation)
                        break
                    except RequestsTimeout:
                        retry_count += 1
                        LOG.warning(f"请求超时，重试次数: {retry_count}")
                        if retry_count >= max_retries:
                            LOG.error("请求超时次数达到最大值，翻译失败")
                            return None, "请求超时次数达到最大值，翻译失败"
                    except Exception as e:
                        retry_count += 1
                        LOG.warning(f"请求失败，重试次数: {retry_count}, 错误信息: {e}")
                        if retry_count >= max_retries:
                            LOG.error("请求失败次数达到最大值，翻译失败")
                            return None, "请求失败次数达到最大值，翻译失败"
                                
                # Update the content in self.book.pages directly
                self.book.pages[page_idx].contents[content_idx].set_translation(translation, status)

        translated_file_path = self.writer.save_translated_book(self.book, output_file_path, file_format) 
        return translated_file_path, ""